package HomeWork2024_2_29;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.stream.Collectors;

public class Work01 {
	public static void main(String[] args) throws IOException {
		String filename = "Test1_sort.txt";
		String str = "2-1-9-4-7-8";
		File file = new File(filename);
		//creatFile(file);
		//WriteFile(file,str);
		ArrayList<String> GetFile = ReadFile(file);
		System.out.println(GetFile);
		String GetFileSort = SortList(GetFile);
		System.out.println(GetFileSort);
		WriteFile(file,GetFileSort);
	}
	private static String SortList(ArrayList<String> getFile) {
		ArrayList<Integer> arr1 = getFile
				.stream()
				.filter(s->(!s.equals("-")))
				.map(s->(Integer.parseInt(s)))
				.collect(Collectors.toCollection(ArrayList::new));
		for(int i=0;i<arr1.size();i++){
			for(int j=0;j<arr1.size();j++){
				int num2 = arr1.get(j);
				int num1 = arr1.get(i);
				if(num1<num2){
					arr1.set(i, num2);
					arr1.set(j, num1);
				}
			}
		}
		ArrayList<String> arr2= arr1.stream()
									.map(num->
		{
			if(num!=arr1.get(arr1.size()-1)){
			return String.valueOf(num).concat("-");
			}
			else{
			return String.valueOf(num);
			}
		}).collect(Collectors.toCollection(ArrayList::new));
		StringBuilder strr = new StringBuilder();
		for(String str:arr2){
			strr.append(str);
		}
		return strr.toString();
	}
	private static ArrayList<String> ReadFile(File file) {
		ArrayList<String> str = new ArrayList<>();
		ArrayList<String> str1 = new ArrayList<>();
		try(FileInputStream fis = new FileInputStream(file);){
			int ch =-1;
			while((ch=fis.read())!=-1){
				str.add((String.valueOf((char)ch)));
			}
		} catch(IOException e){
			e.printStackTrace();
		}
		
		return str;
	}
	private static void WriteFile(File file, String str) {
		
		try (FileOutputStream fos = new FileOutputStream(file);){
			fos.write(str.getBytes());
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	private static void creatFile(File file) throws IOException{
		
		boolean isfilec = file.createNewFile();
		System.out.println(isfilec);
	}
	
}
